package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.config.ThreadContext;
import com.wcs.exam.common.constant.RedisConstant;
import com.wcs.exam.common.enums.TagTypeEnum;
import com.wcs.exam.common.util.BeanUtil;
import com.wcs.exam.controller.admin.req.*;
import com.wcs.exam.controller.admin.resp.AdminTagListResp;
import com.wcs.exam.controller.admin.resp.AdminTagPageResp;
import com.wcs.exam.controller.admin.resp.AdminTagSaveResp;
import com.wcs.exam.controller.admin.resp.AdminTagViewResp;
import com.wcs.exam.dao.po.TagTypeCountPO;
import com.wcs.exam.dao.TagDao;
import com.wcs.exam.dao.TagRecordDao;
import com.wcs.exam.dao.impl.mapper.entity.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Admin-标签信息
 *
 * @author wcs
 * @since 2025-03-17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminTagBiz extends BaseBiz {

    @NotNull
    private final RedissonClient redissonClient;

    @NotNull
    private final TagDao dao;
    @NotNull
    private final TagRecordDao tagRecordDao;

    /**
     * 标签信息-分页
     *
     * @param req 标签信息-分页查询参数
     * @return 标签信息
     */
    public Result<Page<AdminTagPageResp>> page(AdminTagPageReq req) {
        // 处理查询条件
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<Tag>()
                .like(StrUtil.isNotBlank(req.getTagName()), Tag::getTagName, req.getTagName())
                .eq(ObjectUtil.isNotNull(req.getTagType()), Tag::getTagType, req.getTagType())
                .eq(ObjectUtil.isNotNull(req.getStatus()), Tag::getStatus, req.getStatus())
                .orderByDesc(Tag::getSort)
                .orderByDesc(Tag::getId);

        // 分页查询
        IPage<Tag> page = dao.page(PageDTO.of(req.getPageCurrent(), req.getPageSize()), wrapper);
        Page<AdminTagPageResp> respPage = PageUtil.transform(page, AdminTagPageResp.class);
        if (ObjectUtil.isNull(respPage) || CollectionUtil.isEmpty(respPage.getList())) {
            return Result.success(respPage);
        }

        // 汇总统计标签使用情况
        List<Long> tagIdList = respPage.getList().stream().map(AdminTagPageResp::getId).collect(Collectors.toList());
        List<TagTypeCountPO> countList = tagRecordDao.countByTagIds(tagIdList);
        Map<Long, Map<Integer, Integer>> countMap = new HashMap<>(tagIdList.size());
        if (CollectionUtil.isNotEmpty(countList)) {
            countMap = countList.stream().collect(Collectors.groupingBy(TagTypeCountPO::getTagId, Collectors.toMap(TagTypeCountPO::getTagType, TagTypeCountPO::getCount)));
        }

        // 处理标签汇总数据返回
        for (AdminTagPageResp resp : respPage.getList()) {
            Map<Integer, Integer> tagCountMap = countMap.get(resp.getId());
            if (CollectionUtil.isEmpty(tagCountMap)) {
                resp.setUserCount(0);
            } else {
                resp.setUserCount(tagCountMap.getOrDefault(TagTypeEnum.USER.getCode(), 0));
            }
        }
        return Result.success(respPage);
    }

    /**
     * 标签信息-列表
     *
     * @param req 查询参数
     * @return 标签信息
     */
    public Result<List<AdminTagListResp>> list(AdminTagListReq req) {
        // 列出标签信息
        List<Tag> tagList = dao.lambdaQuery()
                .like(StrUtil.isNotBlank(req.getTagName()), Tag::getTagName, req.getTagName())
                .eq(ObjectUtil.isNotNull(req.getTagType()), Tag::getTagType, req.getTagType())
                .eq(ObjectUtil.isNotNull(req.getStatus()), Tag::getStatus, req.getStatus())
                .orderByDesc(Tag::getSort)
                .orderByDesc(Tag::getId)
                .list();
        return Result.success(BeanUtil.copyProperties(tagList, AdminTagListResp.class));
    }

    /**
     * 标签信息-添加
     *
     * @param req 标签信息
     * @return 添加结果
     */
    public Result<String> save(AdminTagSaveReq req) {
        RLock lock = redissonClient.getLock(RedisConstant.Common.TAG_SAVE);

        try {
            // 获取锁
            boolean res = lock.tryLock(RedisConstant.DEFAULT_WAIT_TIME, RedisConstant.DEFAULT_LEASE_TIME, TimeUnit.SECONDS);
            if (!res) {
                log.warn("标签添加获取锁失败");
                return Result.error(toI18nFail());
            }

            // 判断标签是否存在
            Tag tag = dao.getByTagName(req.getTagName());
            if (ObjectUtil.isNotNull(tag)) {
                return Result.error("标签已存在");
            }

            Tag saveTag = BeanUtil.copyProperties(req, Tag.class);
            saveTag.setCreatorId(ThreadContext.getUserId());

            // 排序
            Integer sort = dao.getMaxSort();
            saveTag.setSort(sort + 1);

            boolean saveRes = dao.save(saveTag);
            return saveRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
        } catch (InterruptedException e) {
            log.error("添加标签失败", e);
            Thread.currentThread().interrupt();
            return Result.error(toI18nFail());
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * 标签信息-添加
     *
     * @param req 标签信息-添加对象
     * @return 添加结果
     */
    public Result<AdminTagSaveResp> saveData(AdminTagSaveReq req) {
        RLock lock = redissonClient.getLock(RedisConstant.Common.TAG_SAVE);

        try {
            // 获取锁
            boolean res = lock.tryLock(RedisConstant.DEFAULT_WAIT_TIME, RedisConstant.DEFAULT_LEASE_TIME, TimeUnit.SECONDS);
            if (!res) {
                log.warn("标签添加获取锁失败");
                return Result.error(toI18nFail());
            }

            // 判断标签是否存在
            Tag tag = dao.getByTagName(req.getTagName());
            if (ObjectUtil.isNotNull(tag)) {
                return Result.error("标签已存在");
            }

            Tag saveTag = BeanUtil.copyProperties(req, Tag.class);
            saveTag.setCreatorId(ThreadContext.getUserId());

            // 排序
            Integer sort = dao.getMaxSort();
            saveTag.setSort(sort + 1);

            boolean saveRes = dao.save(saveTag);
            AdminTagSaveResp saveResp = BeanUtil.copyProperties(saveTag, AdminTagSaveResp.class);
            return saveRes ? Result.success(saveResp) : Result.error(toI18nFail());
        } catch (InterruptedException e) {
            log.error("添加标签失败", e);
            Thread.currentThread().interrupt();
            return Result.error(toI18nFail());
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * 标签信息-查看
     *
     * @param id 主键ID
     * @return 标签信息
     */
    public Result<AdminTagViewResp> view(Long id) {
        Tag tag = dao.getById(id);
        if (ObjectUtil.isNull(tag)) {
            return Result.error("标签信息不存在");
        }
        return Result.success(BeanUtil.copyProperties(tag, AdminTagViewResp.class));
    }

    /**
     * 标签信息-编辑
     *
     * @param req 标签信息-编辑对象
     * @return 编辑结果
     */
    public Result<String> edit(AdminTagEditReq req) {
        // 获取校验标签信息
        Tag tag = dao.getById(req.getId());
        if (ObjectUtil.isNull(tag)) {
            return Result.error("标签信息不存在");
        }

        // 判断标签是否重名
        Tag checkTag = dao.getByTagName(req.getTagName());
        if (ObjectUtil.isNotNull(checkTag) && !tag.getId().equals(checkTag.getId())) {
            return Result.error("标签已存在");
        }

        // 更新标签信息
        Tag updateTag = BeanUtil.copyProperties(req, Tag.class);
        updateTag.setGmtCreate(null);
        updateTag.setGmtModified(null);
        boolean updateRes = dao.updateById(updateTag);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 标签信息-编辑状态
     *
     * @param req 标签信息-编辑状态对象
     * @return 编辑结果
     */
    public Result<String> editStatus(AdminTagEditStatusReq req) {
        // 获取校验标签信息
        Tag tag = dao.getById(req.getId());
        if (ObjectUtil.isNull(tag)) {
            return Result.error("标签信息不存在");
        }

        // 更新标签信息
        Tag updateTag = BeanUtil.copyProperties(req, Tag.class);
        updateTag.setGmtCreate(null);
        updateTag.setGmtModified(null);
        boolean updateRes = dao.updateById(updateTag);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 标签信息-排序
     *
     * @param reqs 标签信息-排序对象
     * @return 排序结果
     */
    public Result<String> sort(List<AdminTagSortReq> reqs) {
        // 查询获取标签信息
        List<Tag> tagList = dao.lambdaQuery()
                .in(Tag::getId, reqs.stream().map(AdminTagSortReq::getId).collect(Collectors.toSet()))
                .list();
        if (CollectionUtil.isEmpty(tagList)) {
            return Result.success(toI18nSuccess());
        }

        // 处理待更新排序的标签信息
        Map<Long, Integer> sortMap = new HashMap<>();
        reqs.forEach(item -> sortMap.put(item.getId(), item.getSort()));
        List<Tag> updateList = new ArrayList<>();
        for (Tag tag : tagList) {
            Integer sort = sortMap.get(tag.getId());
            if (ObjectUtil.isNull(sort)) {
                continue;
            }

            Tag updateTag = new Tag();
            updateTag.setId(tag.getId());
            updateTag.setSort(sort);
            updateList.add(updateTag);
        }

        // 批量更新标签信息排序
        if (CollectionUtil.isNotEmpty(updateList)) {
            dao.updateBatchById(updateList);
        }
        return Result.success(toI18nSuccess());
    }

    /**
     * 标签信息-删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        // 获取校验标签信息
        Tag tag = dao.getById(id);
        if (ObjectUtil.isNull(tag)) {
            return Result.error("标签信息不存在");
        }

        // 删除标签记录
        tagRecordDao.deleteByTagId(id);

        // 删除标签信息
        boolean deleteRes = dao.removeById(id);
        return deleteRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }
}
